<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>体测成绩统计（按学校）</span>
        </div>
      </template>
      
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
        <el-form-item label="学校ID" prop="schoolId" required>
          <el-input
            v-model="queryParams.schoolId"
            placeholder="请输入学校ID"
            clearable
            style="width: 300px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery" :loading="loading">
            查询
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 图表展示区域 -->
    <div v-if="resultData && resultData.length > 0">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>测试次数统计</span>
              </div>
            </template>
            <div id="testCountChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>学生人数统计</span>
              </div>
            </template>
            <div id="studentCountChart" style="width: 100%; height: 400px;"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格展示 -->
    <el-card class="box-card result-card" v-if="resultData && resultData.length > 0">
      <template #header>
        <div class="card-header">
          <span>详细数据</span>
          <el-tag type="success">学校ID: {{ queryParams.schoolId }}</el-tag>
          <el-tag type="info">共 {{ resultData.length }} 个年级</el-tag>
        </div>
      </template>
      
      <el-table :data="resultData" stripe>
        <el-table-column prop="gradeId" label="年级ID" min-width="100" />
        <el-table-column label="年级名称" min-width="100">
          <template #default="scope">
            {{ getGradeName(scope.row.gradeId) }}
          </template>
        </el-table-column>
        <el-table-column prop="testCount" label="测试次数" min-width="100" />
        <el-table-column prop="studentCount" label="学生人数" min-width="100" />
        <el-table-column label="人均测试次数" min-width="120">
          <template #default="scope">
            {{ calculateAverage(scope.row) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 空状态提示 -->
    <el-empty description="暂无数据" v-if="!loading && (!resultData || resultData.length === 0)" />
  </div>
</template>

<script setup name="TcfxView">
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts';
import { getGradeView } from "@/api/tc/tcsj";

const { proxy } = getCurrentInstance();

const queryParams = reactive({
  schoolId: ''
});

const loading = ref(false);
const resultData = ref(null);
const chartsInitialized = ref(false);

// 年级ID到名称的映射
const gradeMap = {
  '14': '一年级',
  '15': '二年级', 
  '16': '三年级',
  '17': '四年级',
  '18': '五年级',
  '19': '六年级',
  '20': '初一',
  '21': '初二',
  '22': '初三',
  '23': '高一',
  '24': '高二',
  '25': '高三'
};

// 获取年级名称
function getGradeName(gradeId) {
  return gradeMap[gradeId] || `年级${gradeId}`;
}

// 初始化图表
const initCharts = () => {
  if (chartsInitialized.value) return;
  
  nextTick(() => {
    setTimeout(() => {
      const testCountChart = echarts.getInstanceByDom(document.getElementById('testCountChart'));
      const studentCountChart = echarts.getInstanceByDom(document.getElementById('studentCountChart'));
      
      if (!testCountChart && document.getElementById('testCountChart')) {
        window.testCountChartInstance = echarts.init(document.getElementById('testCountChart'));
      }
      if (!studentCountChart && document.getElementById('studentCountChart')) {
        window.studentCountChartInstance = echarts.init(document.getElementById('studentCountChart'));
      }
      
      chartsInitialized.value = true;
    }, 100);
  });
};

// 渲染图表
const renderCharts = (data) => {
  if (!data || data.length === 0) return;
  
  // 确保图表已经初始化
  initCharts();
  
  nextTick(() => {
    setTimeout(() => {
      const gradeNames = data.map(item => getGradeName(item.gradeId));
      const testCounts = data.map(item => item.testCount);
      const studentCounts = data.map(item => item.studentCount);

      // 测试次数图表配置
      const testCountOption = {
        title: {
          text: '各年级测试次数统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}次'
        },
        xAxis: {
          type: 'category',
          data: gradeNames,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '测试次数'
        },
        series: [{
          name: '测试次数',
          type: 'bar',
          data: testCounts,
          itemStyle: {
            color: '#5470c6'
          },
          label: {
            show: true,
            position: 'top'
          }
        }]
      };

      // 学生人数图表配置
      const studentCountOption = {
        title: {
          text: '各年级学生人数统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}人'
        },
        xAxis: {
          type: 'category',
          data: gradeNames,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '学生人数'
        },
        series: [{
          name: '学生人数',
          type: 'bar',
          data: studentCounts,
          itemStyle: {
            color: '#91cc75'
          },
          label: {
            show: true,
            position: 'top'
          }
        }]
      };

      // 渲染图表
      try {
        if (window.testCountChartInstance && typeof window.testCountChartInstance.setOption === 'function') {
          window.testCountChartInstance.setOption(testCountOption);
          window.testCountChartInstance.resize();
        } else {
          console.error('testCountChartInstance 未正确初始化');
        }
        
        if (window.studentCountChartInstance && typeof window.studentCountChartInstance.setOption === 'function') {
          window.studentCountChartInstance.setOption(studentCountOption);
          window.studentCountChartInstance.resize();
        } else {
          console.error('studentCountChartInstance 未正确初始化');
        }
      } catch (error) {
        console.error('图表渲染错误:', error);
      }
    }, 200);
  });
};

// 计算平均测试次数
function calculateAverage(row) {
  if (!row.studentCount || row.studentCount === 0) return '0';
  return (row.testCount / row.studentCount).toFixed(1);
}

/** 查询操作 */
function handleQuery() {
  if (!queryParams.schoolId) {
    ElMessage.warning('请输入学校ID');
    return;
  }

  if (isNaN(queryParams.schoolId)) {
    ElMessage.warning('学校ID必须为数字');
    return;
  }

  loading.value = true;
  resultData.value = null;

  getGradeView(queryParams.schoolId)
    .then(response => {
      resultData.value = response.data;
      ElMessage.success('查询成功');
      // 渲染图表
      renderCharts(response.data);
    })
    .catch(error => {
      console.error('查询失败:', error);
      ElMessage.error('查询失败: ' + (error.message || '未知错误'));
      resultData.value = null;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryParams.schoolId = '';
  resultData.value = null;
  
  // 清空图表
  if (window.testCountChartInstance) {
    window.testCountChartInstance.clear();
  }
  if (window.studentCountChartInstance) {
    window.studentCountChartInstance.clear();
  }
}

// 组件挂载时初始化图表
onMounted(() => {
  initCharts();
  
  // 窗口调整时重绘图表
  window.addEventListener('resize', () => {
    if (window.testCountChartInstance) {
      window.testCountChartInstance.resize();
    }
    if (window.studentCountChartInstance) {
      window.studentCountChartInstance.resize();
    }
  });
});

// 组件卸载时清理
onUnmounted(() => {
  if (window.testCountChartInstance) {
    window.testCountChartInstance.dispose();
    window.testCountChartInstance = null;
  }
  if (window.studentCountChartInstance) {
    window.studentCountChartInstance.dispose();
    window.studentCountChartInstance = null;
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.result-card {
  margin-top: 20px;
}

:deep(.el-table) {
  margin-top: 10px;
}

:deep(.el-input) {
  width: 300px;
}

:deep(.el-col) {
  margin-bottom: 20px;
}
</style>